package dome2;

public class BinarySearchTree {

    static class TreeNode {
        public int key;
        public TreeNode left;
        public TreeNode right;

        TreeNode(int key) {
            this.key = key;
        }
    }

    public TreeNode root;

    /**
     * 插入一个元素
     * @param key
     */
    public boolean insert(int key) {
        TreeNode node = new TreeNode(key);
        if(root == null) {
            root = node;
            return true;
        }
        TreeNode prev = null;
        TreeNode cur = root;
        while(cur != null) {
            if(cur.key < key ) {
                prev = cur;
                cur = cur.right;
            }else if(cur.key > key) {
                prev = cur;
                cur = cur.left;
            }else {
                return false;
            }
        }
        if(prev.key > key) {
            prev.left = node;
        }else {
            prev.right = node;
        }
        return true;
    }
    //查找key是否存在
    public TreeNode search(int key) {
        if(root == null) root.key = key;
        while(root != null) {
            if(root.key < key ) {
                root = root.right;
            }else if(root.key > key) {
                root = root.left;
            }else {
                return root;
            }
        }
        return null;
    }
    //删除key的值
    public boolean remove(int key) {
        TreeNode cur = root;
        TreeNode prev = null;
        while(cur!=null) {
            if(cur.key < key) {
                prev = cur;
                cur = cur.right;
            }else if(cur.key > key) {
                prev = cur;
                cur = cur.left;
            }else {
                removenode(prev,cur,key);
                return true;
            }
        }
        return false;
    }

    private void removenode(TreeNode prev, TreeNode cur, int key) {
        if(cur.left==null) {
            if(cur == root) {
                root = root.right;
            }
            if(prev.left == cur) {
                prev.left = cur.right;
            }else {
                prev.right = cur.right;
            }
        }else if(cur.right == null) {
            if(cur == root) {
                root = root.left;
            }
            if(prev.left == cur) {
                prev.left = cur.left;
            }else {
                prev.right = cur.left;
            }
        }else {
            TreeNode targetPrev = cur;
            TreeNode target = cur.left;
            while(target.right!=null) {
                targetPrev = target;
                target = target.right;
            }
            cur.key = target.key;
            if(targetPrev.left == target) {
                targetPrev.left = target.left;
            }else {
                targetPrev.right = target.left;
            }
        }
    }
}